import React, { useEffect, useState } from 'react';
import { Button, Modal, Space, Table, Tag } from 'antd';
import type { TableProps } from 'antd';
import http from '../../api/http';
import type { FormProps } from 'antd';
import { Checkbox, Form, Input } from 'antd';

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}

const App: React.FC = () => {
  // 定义表格数据
  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [title, setTitle] = useState('')
  const [tag, setTag] = useState('')
  const [forms] = Form.useForm();
  const [form] = Form.useForm();

  // 获取数据
  const FetchData = async () => {
    const params: {
      page: number,
      pageSize: number,
      keyword?: string,//搜索标题
      tag?: string
    } = {
      page, pageSize
    }
    if (title) params.keyword = title
    if (tag) params.tag = tag
    const res = await http.get('/article/list', {
      params
    })
    console.log(res, '列表')
    setData(res.data.rows)
    setTotal(res.data.count)
  }
  // 回调函数
  useEffect(() => {
    FetchData()
  }, [page, pageSize, title, tag])

  // 分页
  const change = (page: number, pageSize: number) => {
    setPage(page)
    setPageSize(pageSize)
  }

  // 搜索
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  // 重置
  const handleReact = () => {
    setTitle('')
    setTag('')
    forms.resetFields()
  }

  // 弹框
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [flag, setFlag] = useState(false);

  const handleEdit = (row) => {
    setOpen(true)
    setFlag(true)
    form.setFieldsValue(row)
  }

  // 新增/编辑
  const handleOk = async () => {
    setFlag(true)
    const { id, title, content } = form.getFieldsValue()
    if (!flag) {
      const res = await http.post('/article', {
        title,
        content,
        tagList: ["新增接口"],//标签  array[string]
        categoryList: ["前端"],//分类  array[string]
        authorId: '47529555'
      })
      console.log(res, '新增数据')
      setOpen(false)
      setConfirmLoading(false)
      FetchData()
      form.resetFields()
    } else {
      const res = await http.put(`/article/${id}`, {
        title,
        content,
        tagList: ["编辑接口"],//标签  array[string]
        categoryList: ["IT"],//分类  array[string]
        authorId: '47529555'
      })
      console.log(res, '编辑数据')
      setOpen(false)
      setConfirmLoading(false)
      FetchData()
      form.resetFields()
    }
  };

  // 取消
  const handleCancel = () => {
    console.log('取消');
    setOpen(false);
  };

  // 渲染数据
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'First Name',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: 'Last Name',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: 'username',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: 'Start time',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: 'End Time',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : '#ccc';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button color="default" variant="outlined" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button color="danger" variant="solid">
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 表单搜索 */}
      <Form
        name="basic"
        layout='inline'
        form={forms}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType>
          label="First Name"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item<FieldType>
          label="标签"
          name="tag"
        >
          <Input />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" onClick={() => handleReact()}>
            重置
          </Button>
        </Form.Item>

      </Form>
      <hr />
      <Button color="default" variant="solid" onClick={() => setOpen(true)}>
        新增数据 +
      </Button>
      {/* 表格 */}
      <Table<DataType>
        columns={columns}
        dataSource={data}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: change
        }}
      />
      {/* 弹框 */}
      <Modal
        title="Title"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="ID"
            name="id"
          >
            <Input disabled />
          </Form.Item>

          <Form.Item<FieldType>
            label="First Name"
            name="title"
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label="内容"
            name="content"
          >
            <Input />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  )
}

export default App;